<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/3/27
 * Time: 10:33
 */

namespace app\admin\model;

use app\company\model\CompanyGoods;
use app\company\model\CompanyGoodsRule;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Model;


/**
 * @property  int $id
 * @property  string $name 商品名称
 * @property  string $no 商品编码
 * @property  string $img 商品图片
 * @property  string $unit 商品单位
 * @property  int $spec_type 规格类型 1:单规格,2:多规格',
 * @property  int $shelf_life 保质期(天)
 * @property  int $status 商品状态  1:上架,2:下架',
 * @property  int $racking_time 上架时间
 * @property  int $sold_out_time 下架时间
 */
class Goods extends Base
{

    public static function onBeforeInsert(Goods $model): void
    {
        $model->racking_time = time();
    }

    /**
     * @param Goods $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public static function onAfterInsert(Goods $model): void
    {
        $model->no = 'GOODS' . getPaddedNumber($model->id, 10);
        $param     = Request::param();
        //规格组处理
        if (request()->param('attrs', 0)) {
            self::attrsFormat($param['attrs'], $model->id);
        }
        //添加商品规格
        foreach ($param['specs'] as $v) {
            $v['goods_id'] = $model->id;
            (new GoodsRule)->save($v);
        }

    }

    public static function onAfterUpdate(Goods $model): void
    {
        CompanyGoods::where('goods_id',$model->id)
                    ->where('goods_cate_id',$model->goods_cate_id)
                    ->update(['descriptions'=>$model->descriptions]);
    }


    /**
     * @param Goods $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public static function onBeforeUpdate(Goods $model): void
    {
        if(request()->param('shelf_life', 0) > 29470){
            exception('商品有效期不能超过29470天');
        }
        $param = Request::param();
        //规格组处理
        if (request()->param('attrs', 0)) {
            self::attrsFormat($param['attrs'], $model->id);
        }
        //添加商品规格
        // 都在这处理过一次了，为啥还要在下面再处理一次？不怕数据重复或者出问题吗？
//        if (request()->param('specs', 0)) {
//            foreach ($param['specs'] as &$v) {
//                if (!$goodsRule = GoodsRule::where('spec_name', $v['spec_name'])->where('goods_id', $model->id)->find()) {
//                    $goodsRule = new GoodsRule();
//                }
//                $v['goods_id'] = $model->id;
//                $goodsRule->save($v);
//            }
//        }
        //修改多规格和单规格
        if (request()->param('spec_type', 0)) {
            // 2024.09.27 有个问题，现在如果删除再修改，因为共用的一个商品库，删了再加会影响其他库
            // 只能先处理单规格的商品，让前端传个规格ID进来
            if(request()->param('spec_type', 0) == 1){
                // 单规格
                foreach ($param['specs'] as &$v) {
                    $where = [
                        'spec_name' => $v['spec_name']
                    ];
                    if(!empty($v['id'])){
                        $where = [
                            'id' => $v['id']
                        ];
                    }
                    $goodsRule = GoodsRule::where($where)->where('goods_id', $model->id)->where('delete_time',0)->find();
                    $v['goods_id'] = $model->id;
                    $goodsRule->save($v);
                }
            }else{// 多规格
                //删除关联规格,重新添加
                if ($model->goodsRules()->count()) $model->goodsRules->delete();
                //删除关联规格组,重新添加
                if ($model->goodsSpecs()->count()) $model->goodsSpecs->delete();
                self::attrsFormat($param['attrs'], $model->id);
                foreach ($param['specs'] as &$v) {
                    $goodsRule     = new GoodsRule();
                    $v['goods_id'] = $model->id;
                    $goodsRule->save($v);
                }
            }
        }

        if (request()->param('status', 0)) {
            if ($param['status'] == 1) $model->racking_time = time();
            if ($param['status'] == 2) $model->sold_out_time = time();
            $model->goodsRules->update(['status' => $param['status']]);
        }
    }

    /**
     * 添加/修改时触发该操作
     * @param $attrs
     * @param $goods_id
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function attrsFormat($attrs, $goods_id): void
    {
        foreach ($attrs as $k => $v) {
            if (!$Spec = GoodsSpec::where('goods_id', $goods_id)->where('name', $k)->find()) {
                $Spec = new GoodsSpec();
            }
            $arr['goods_id'] = $goods_id;
            $arr['name']     = $k;
            $arr['value']    = $v;
            $Spec->save($arr);
        }
    }

    public static function onBeforeDelete(Goods $model)
    {
        $model->goodsRules->delete();
        //删除所有公司商品
        if ($model->companyGoodss()->count()) $model->companyGoodss->delete();
        //删除所有公司商品
        if ($model->companyGoodsRules()->count()) $model->companyGoodsRules->delete();
    }


}

